<template>
  <div>
    <el-table
      ref="refTable"
      v-loading="isFetching"
      :data="tableData"
      element-loading-text="Loading"
      fit
      style="width: 100%"
      @cell-dblclick="handleCellDblclick">
      <el-table-column fixed type="expand">
        <template slot-scope="{ row }">
          <el-form
            :ref="`diagnose3_form${row.__fid}`"
            label-position="left"
            inline
            class="table_expand"
            label-width="100px"
            size="small">
            <div style="width: 90%; display: flex; flex-direction: row; justify-content: flex-start; gap: 50px">
              <div>
                <el-form-item label="业绩年月">
                  <el-date-picker
                    v-model="row.reviewMonth"
                    type="month"
                    format="yyyy-MM"
                    value-format="yyyy-MM"
                    :disabled="row.id && row.id > 0"
                    style="width: 180px"></el-date-picker>
                </el-form-item>
                <el-form-item label="总业绩">
                  <el-input-number
                    v-model="row.totalPerformance"
                    :step="1"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="到院老客量">
                  <el-input-number
                    v-model="row.oldClerkCount"
                    :step="1"
                    :min="0"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="老客单均价">
                  <el-input-number
                    v-model="row.oldClerkAvg"
                    :step="1"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <!--操作-->
                <el-form-item>
                  <el-button v-if="isUpdating" type="primary" disabled icon="el-icon-loading" style="width: 120px">
                    提交中
                  </el-button>
                  <el-button
                    v-else-if="row.id === undefined"
                    type="primary"
                    @click="handleSubmitForm(`diagnose3_form${row.__fid}`, true, row)">
                    保存
                  </el-button>
                  <el-button v-else type="warning" @click="handleSubmitForm(`diagnose3_form${row.__fid}`, false, row)">
                    修改
                  </el-button>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="到院新客量">
                  <el-input-number
                    v-model="row.newClerkCount"
                    :step="1"
                    :min="0"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="新客单均价">
                  <el-input-number
                    v-model="row.newClerkAvg"
                    :step="1"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="业绩活动">
                  <el-switch v-model="row.hasPerformanceActivity"></el-switch>
                </el-form-item>
                <el-form-item label="活动业绩">
                  <el-input-number
                    v-model="row.activityPerformance"
                    :step="1"
                    :min="0"
                    :max="row.totalPerformance"
                    :precision="2"
                    controls-position="right"
                    :disabled="!row.hasPerformanceActivity"
                    style="width: 180px"></el-input-number>
                </el-form-item>
                <el-form-item label="信息来源">
                  <el-input
                    v-model="row.infoSource"
                    type="textarea"
                    maxlength="128"
                    show-word-limit
                    style="width: 180px"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column fixed prop="reviewMonth" label="业绩年月" align="center"></el-table-column>
      <el-table-column prop="totalPerformance" label="总业绩" align="center"></el-table-column>
      <el-table-column prop="oldClerkCount" label="到院老客量" align="center"></el-table-column>
      <el-table-column prop="oldClerkAvg" label="老客单均价" align="center"></el-table-column>
      <el-table-column prop="newClerkCount" label="到院新客量" align="center"></el-table-column>
      <el-table-column prop="newClerkAvg" label="新客单均价" align="center"></el-table-column>
      <el-table-column prop="hasPerformanceActivity" label="业绩活动" align="center">
        <template slot-scope="{ row }">{{ row.hasPerformanceActivity ? '有' : '无' }}</template>
      </el-table-column>
      <el-table-column prop="activityPerformance" label="活动业绩" align="center"></el-table-column>
      <el-table-column
        prop="infoSource"
        label="信息来源"
        align="center"
        width="120"
        show-overflow-tooltip></el-table-column>
      <el-table-column
        prop="coachName"
        label="复盘教练"
        align="center"
        width="100"
        show-overflow-tooltip></el-table-column>
      <el-table-column prop="createDate" label="复盘日期" align="center" width="120">
        <template slot-scope="{ row }">{{ row.createDate ? row.createDate.substring(0, 11) : '--' }}</template>
      </el-table-column>
      <el-table-column fixed="right" align="center" width="120">
        <template slot="header">
          <el-button type="primary" size="mini" plain @click.stop="handleAddEmptyRow">添加一行</el-button>
        </template>
        <template slot-scope="{ row }">
          <el-button v-if="row.id && row.id > 0" type="danger" size="mini" plain @click.stop="handleDelete(row)">
            删除
          </el-button>
          <el-button v-else type="warning" size="mini" plain @click.stop="handleDeleteRow(row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { delPerfDiagnoseById, getPerfDiagnoseByNo, savePerfDiagnoseByNo } from '@/api/diagnose';
// 引入自定义组件
import '@/utils/datefmt';
// 引入第三方组件
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const EmptyPerfData = {
  id: undefined,
  reviewMonth: new Date().format('yyyy-MM'),
  totalPerformance: 0.0,
  oldClerkCount: 0,
  oldClerkAvg: 0.0,
  newClerkCount: 0,
  newClerkAvg: 0.0,
  hasPerformanceActivity: 0,
  activityPerformance: 0.0,
  infoSource: '',
  coachId: null,
  coachName: null,
  createDate: new Date().format('yyyy-MM-dd HH:mm:ss'),
  __fid: '', // Form 表单ID
};

export default {
  name: 'Diagnose3',
  data() {
    return {
      tableData: [],
      salon: {},
      rules: {},
      isFetching: false, // 通用的&互斥的, 加载后端数据
      isUpdating: false,
      curEditCell: undefined, // 当前编辑的单元格: 主键id + "_" + 单元格属性名(prop)
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
  },
  methods: {
    loadDiagnoseData: async function (salon /* {salonId: '', salonNo: '', salonName: '', diagnoseNo: ''} */) {
      if (!salon || !salon.diagnoseNo) {
        return;
      }
      this.salon = Object.assign({}, salon);
      this.loadDiagnose3();
    },
    loadDiagnose3: async function () {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      this.tableData.splice(0, this.tableData.length);
      const errAlertMsg = '查询业绩复盘信息失败';
      await getPerfDiagnoseByNo(this.salon.diagnoseNo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length > 0) {
            // ret 按照 reviewMonth 升序排序
            ret.sort((a, b) => new Date(a.reviewMonth) - new Date(b.reviewMonth));
            ret.forEach(x => {
              if (x.hasPerformanceActivity === 1) {
                x.hasPerformanceActivity = true;
              } else {
                x.hasPerformanceActivity = false;
              }
              x.__fid = this.getRadomStr6();
              this.tableData.push(x);
            });
          }
        })
        .catch(err => {
          console.log('getPerfDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    handleCellDblclick: async function (row, column, cell, event) {
      const target = event.target || event.srcElement;
      const nodeName = target.nodeName;
      if (!row || !column || !cell || nodeName !== 'DIV') {
        return;
      }
      // this.curEditCell = `${row.id}_${column.property}`;
      // console.log('curEditCell', this.curEditCell);
    },
    handleAddEmptyRow: async function () {
      const cpy = Object.assign({}, EmptyPerfData);
      cpy.coachName = this.name;
      cpy.__fid = this.getRadomStr6();
      this.tableData.push(cpy);
    },
    handleDelete: async function (row) {
      const errAlertMsg = '删除业绩复盘信息失败';
      delPerfDiagnoseById(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.handleDeleteRow(row);
        })
        .catch(err => {
          console.log('delPerfDiagnoseById', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    handleDeleteRow: async function (row) {
      // 根据 index 从 this.tableData 中将数据删除
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData.splice(index, 1);
      }
    },
    getRadomStr6() {
      // 生成长度为 6 的随机字符串
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    handleSubmitForm: async function (formName, isadd, row) {
      // Validate row data against rules
      for (const key in this.rules) {
        if (this.rules.hasOwnProperty(key)) {
          const rule = this.rules[key][0];
          if (rule.required && (row[key] === undefined || row[key] === null)) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'array' && row[key].length < rule.min) {
            MessageBox.alert(rule.message);
            return;
          }
          if (rule.type === 'number' && typeof row[key] !== 'number') {
            MessageBox.alert(rule.message);
            return;
          }
        }
      }

      if (isadd) {
        // 检查 reviewMonth 在 tableData 中是否已存在
        const reviewMonths = this.tableData.map(item => item.reviewMonth);
        const hasDuplicates = reviewMonths.some((item, index) => reviewMonths.indexOf(item) !== index);
        if (hasDuplicates) {
          MessageBox.alert('该业绩年月已存在，请勿重复添加');
          return;
        }
      }

      if (this.isUpdating) {
        return;
      }
      if (row.id === undefined) {
        row.id = null;
      }
      if (row.hasPerformanceActivity) {
        row.hasPerformanceActivity = 1;
      } else {
        row.hasPerformanceActivity = 0;
      }

      this.isUpdating = true;
      const errAlertMsg = '保存业绩复盘信息失败';
      savePerfDiagnoseByNo(this.salon.diagnoseNo, row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          this.loadDiagnose3();
          MessageBox.alert('保存成功');
        })
        .catch(err => {
          console.log('savePerfDiagnoseByNo', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.table_expand {
  padding: 5px 16px;
  font-size: 0;
  background-color: rgb(249, 243, 234);
}
.table_expand label {
  width: 90px;
  color: #99a9bf;
}
.table_expand .el-form-item {
  margin-right: 0;
  margin-bottom: 5px;
  width: 50%;
}
</style>
